<template>
  <div>
    <h1>订单列表</h1>
    <el-form :inline="true" :model="form" class="demo-form-inline">
      <el-form-item label="关键字">
        <el-input v-model="form.keyWord" placeholder="id/信息" clearable />
      </el-form-item>

      <el-form-item label="订单状态">
        <el-select
          v-model="form.orderStatus"
          placeholder="请选择订单状态"
          clearable
        >
          <el-option label="未支付" :value="0" />
          <el-option label="已支付" :value="1" />
          <el-option label="待发货" :value="2" />
        </el-select>
      </el-form-item>

      <el-form-item label="订单类型">
        <el-select
          v-model="form.typeId"
          placeholder="请选择订单理性"
          style="width: 240px"
          clearable
        >
          <el-option
            v-for="item in Typeoptions"
            :key="item.dictValue"
            :label="item.dictName"
            :value="item.dictValue"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="getOrder()">查询</el-button>
      </el-form-item>
    </el-form>
    <el-button type="primary" @click="showOrder">添加订单</el-button>
    <el-button type="primary" @click="excelorder">导出订单信息</el-button>
    <el-button type="danger" @click="batchDelete">批量删除</el-button>
    <el-table
      :data="tableData"
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="orderId" label="ID" />
      <el-table-column prop="orderNo" label="订单编号" />
      <el-table-column prop="prodInfo" label="商品信息" />
      <el-table-column prop="orderAmount" label="订单金额" />
      <el-table-column prop="createTime" label="创建时间" />
      <el-table-column prop="createBy" label="消费者" />
      <el-table-column
        prop="orderType"
        :formatter="formatter"
        label="订单类型"
      />
      <el-table-column prop="imageList" label="商品图片">
        <template #default="scope">
          <el-image
            style="width: 40px; height: 40px"
            :src="scope.row.imageList"
          />
        </template>
      </el-table-column>
      <el-table-column prop="orderStatus" label="订单状态">
        <template #default="scope">
          <el-tag type="danger" v-if="scope.row.orderStatus == 0"
            >未支付</el-tag
          >
          <el-tag type="primary" v-if="scope.row.orderStatus == 1"
            >已支付</el-tag
          >
          <el-tag type="success" v-if="scope.row.orderStatus == 2"
            >待发货</el-tag
          >
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button type="primary" size="small" @click="orderinfo(scope.row)"
            >详情</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <div class="demo-pagination-block">
      <el-pagination
        v-model:current-page="form.pageNum"
        v-model:page-size="form.pageSize"
        :page-sizes="[2, 3, 4, 5]"
        :background="true"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
  <div>
    <el-dialog v-model="dialogFormVisible" title="新增订单" width="600">
      <el-form
        :model="form"
        ref="ruleFormRef"
        style="max-width: 600px"
        :rules="rules"
      >
        <el-form-item
          label="商品信息"
          :label-width="formLabelWidth"
          prop="infoId"
        >
          <el-select
            v-model="form.infoId"
            placeholder="请选择商品信息"
            size="large"
            style="width: 240px"
          >
            <el-option
              v-for="item in InfoOptions"
              :key="item.infoId"
              :label="item.prodName"
              :value="item.infoId"
            />
          </el-select>
        </el-form-item>

        <el-form-item
          label="购买数量"
          :label-width="formLabelWidth"
          prop="buyNum"
        >
          <el-input v-model="form.buyNum" autocomplete="off" />
        </el-form-item>
        <div>
          <el-button type="primary" @click="addProdInfo">添加</el-button>
        </div>
        <div>
          <el-table :data="prodInfoList" stripe style="width: 100%">
            <el-table-column prop="prodId" label="商品ID" />
            <el-table-column prop="prodName" label="商品名称" />
            <el-table-column prop="prodPrice" label="商品价格" />
            <el-table-column prop="buyNum" label="购买数量" />
            <el-table-column label="操作">
              <template #default="scope">
                <el-button
                  type="danger"
                  size="small"
                  @click="deleteInfo(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <div>总价:{{ totalAmount }}元</div>
        </div>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm(ruleFormRef)">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import { onMounted, ref } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  getOrderList,
  getDictListByTypeId,
  getProdInfo,
  addOrder,
  deleteBatchOrder,
} from "../api/api";
import { json } from "stream/consumers";
import type { FormInstance, FormRules } from "element-plus";
const tableData = ref([]);
const total = ref(0);
const Typeoptions = ref([]);
const userId = ref(0);
const prodInfoList = ref([]);
const dialogFormVisible = ref(false);
const formLabelWidth = "140px";
const InfoOptions = ref([]);
const totalAmount = ref(0);
const multipleSelection = ref<any[]>([]);
const ruleFormRef = ref<FormInstance>();
const form = ref({
  keyWord: "",
  orderStatus: null,
  pageNum: 1,
  pageSize: 2,
  typeId: null,
  infoId: null,
  buyNum: 1,
});
const rules = ref<FormRules>({
  infoId: [{ required: true, message: "请选择商品", trigger: "change" }],
  buyNum: [{ required: true, message: "请输入购买数量", trigger: "blur" }],
});
const batchDelete = () => {
  let ids = [];
  if (multipleSelection.value.length == 0) {
    ElMessage.error("请先选择订单");
    return;
  }
  multipleSelection.value.forEach((item) => {
    ids.push(item.orderId);
  });

  ElMessageBox.confirm("你确定删除吗?", "警告", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      deleteBatchOrder(ids).then((res) => {
        if (res.data.code == 200) {
          ElMessage.success("删除成功");
          getOrder();
        }
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除",
      });
    });
};
const handleSelectionChange = (val: any[]) => {
  multipleSelection.value = val;
};
const showOrder = () => {
  prodInfoList.value = [];
  form.value = {
    infoId: null,
    buyNum: 1,
  };
  dialogFormVisible.value = true;
};
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log("submit!");
      addOrder(prodInfoList.value).then((res) => {
        if (res.data.code == 200) {
          ElMessage.success("添加成功");
          dialogFormVisible.value = false;
          getOrder();
        } else {
          ElMessage.error(res.data.msg);
        }
      });
    } else {
      console.log("error submit!", fields);
    }
  });
};
const addProdInfo = () => {
  InfoOptions.value.forEach((item) => {
    if (item.infoId === form.value.infoId) {
      item.buyNum = form.value.buyNum;
      prodInfoList.value.push(item);
    }
  });
  totalAmount.value = 0.0;
  prodInfoList.value.forEach((item) => {
    totalAmount.value += item.prodPrice * item.buyNum;
  });
};
const deleteInfo = (row: any) => {
  prodInfoList.value.forEach((item, index) => {
    if (item.infoId === row.infoId) {
      prodInfoList.value.splice(index, 1);
    }
  });
};
const excelorder = () => {
  //打开路径网址、
  let url = "http://localhost:9022//product/index/excelPage/" + userId.value;
  window.open(url);
};
const formatter = (row: any) => {
  let name = "";
  Typeoptions.value.forEach((item: any) => {
    if (item.dictValue == row.orderType) {
      name = item.dictName;
    }
  });
  return name;
};
const getOrder = () => {
  getOrderList(form.value).then((res) => {
    if (res.data.code == 200) {
      tableData.value = res.data.data.records;
      total.value = res.data.data.total;
    }
  });
};
const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`);
  form.value.pageSize = val;
  getOrder();
};
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`);
  form.value.pageNum = val;
  getOrder();
};
onMounted(() => {
  getOrder();
  getProdInfo().then((res) => {
    if (res.data.code == 200) {
      InfoOptions.value = res.data.data;
    }
  });
  getDictListByTypeId(4).then((res) => {
    Typeoptions.value = res.data.data;
  });
  let user = JSON.parse(sessionStorage.getItem("user"));
  userId.value = user.userId;
});
</script>
<style>
.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}
</style>
